package com.zkn.component.office.excel;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zkn.component.office.excel.handler.ExcelFieldHandler;
import com.zkn.component.office.excel.utils.ExcelUtils;

/**
 * Excel Reader
 * @author FrankSu
 * @date 2017/08/01
 */
public class ExcelReader {
	
	/*
	 * TODO
	 * 1. Read Workbook.
	 * 2. Read data from Workbook.
	 * 3. Release.
	 */
	
	/**
	 * readExcel2ObjectList
	 * @param filepath
	 * @param clazz
	 * @return
	 * @throws Exception
	 * @author frank.su
	 */
	public static <T> List<T> readExcel2ObjectList(String filepath, Class<T> clazz) throws Exception{
		List<Map<String,Object>> dataList = readExcel2MapList(filepath, true);
		return ExcelFieldHandler.handle(dataList, clazz);
	}
	
	/**
	 * readExcel2MapList
	 * @param filepath
	 * @return
	 * @throws Exception
	 * @author frank.su
	 */
	public static List<Map<String,Object>> readExcel2MapList(String filepath, boolean isFirstSheet) throws Exception{
		return readExcel2MapList(new FileInputStream(filepath), isFirstSheet);
	}
	
    /**
     * readExcel2MapList
     * @param is
     * @return
     * @throws Exception
     * @author frank.su
     */
    public static List<Map<String,Object>> readExcel2MapList(InputStream is, boolean isFirstSheet) throws Exception{
        return ExcelUtils.readExcel2MapList(is, isFirstSheet);
   }
    
    /**
     * readExcel2StringList
     * @param is
     * @return
     * @throws Exception
     * @author frank.su
     */
    public static List<List<String>> readExcel2StringList(String filepath, boolean isFirstSheet) throws Exception{
    	return readExcel2StringList(new FileInputStream(filepath), isFirstSheet);
    }
    
    /**
     * readExcel2StringList
     * @param is
     * @return
     * @throws Exception
     * @author frank.su
     */
    public static List<List<String>> readExcel2StringList(InputStream is, boolean isFirstSheet) throws Exception{
    	return ExcelUtils.readExcel2StringList(is, isFirstSheet);
    }
    
    /**
     * Read data from excel.
     * @param fields
     * @param filepath
     * @return
     * @throws Exception
     * @author frank.su
     */
    public static List<Map<String,Object>> readExcel2MapList(String[] fields, String filepath, boolean isFirstSheet) throws Exception{
    	List<Map<String,Object>> resultList= new ArrayList<Map<String,Object>>();
    	
    	List<Map<String,Object>> mapList = readExcel2MapList(filepath, isFirstSheet);
    	if(!mapList.isEmpty()){
    		for (Map<String, Object> map : mapList) {
    			Map<String, Object> result = new HashMap<String, Object>();
    			for (String filed : fields) {
    				result.put(filed, map.get(filed));
    			}
    			resultList.add(result);
    		}
		}
    	return resultList;
    }
}
